<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Db;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * @property int $id
 * @property string $order_no
 * @property string $pay_id
 * @property int $level
 * @property int $start_date
 * @property int $renew
 * @property int $type
 * @property int $create_time
 * @property int $status
 * @property string $price
 * @property int $uid
 * @property string $account
 * @property string $code
 * @property string $original_transaction_id
 * @property string $original_purchase_date_ms
 * @property string $web_order_line_item_id
 * @property int $expires_date_ms
 * @property string $receipt_data
 * @property int $update_time
 */
class OrderSubscribe extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'order_subscribe';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['id', 'order_no', 'pay_id', 'level', 'start_date', 'renew', 'type', 'create_time', 'status', 'price', 'uid', 'account', 'code', 'original_transaction_id', 'original_purchase_date_ms', 'web_order_line_item_id', 'expires_date_ms', 'receipt_data', 'update_time'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'level' => 'integer', 'start_date' => 'integer', 'renew' => 'integer', 'type' => 'integer', 'create_time' => 'integer', 'status' => 'integer', 'uid' => 'integer', 'expires_date_ms' => 'integer', 'update_time' => 'integer'];


    public static function createSubscribeOrder($uid, $code)
    {

        $userInfo = User::where(['id' => $uid])->first();
        if (is_null($userInfo)) {
            return false;
        }

        $orderNo = self::createOrderNo();

        $subInfo = SubOption::where(['code' => $code])->first();
        if (empty($subInfo)) {
            return false;
        }

        $data = [
            'order_no' => $orderNo,
            'uid' => $uid,
            'account' => $userInfo['account'],
            'level' => $subInfo['unit'],
            'type' => 1,
            'price' => $subInfo['price'],
            'code' => $code,
            'create_time' => time(),
            'status' => 0
        ];


        $rel = self::insert($data);

        if ($rel) {
            return $orderNo;
        } else {
            return false;
        }

    }


    public static function createOrderNo()
    {
        $orderNo = date('ymd', time()) . substr(microtime(), 2, 3) . sprintf('%05d', rand(0, 99999));
        $exists = self::where(['order_no' => $orderNo])->exists();
        if ($exists) {
            self::createOrderNo();
        } else {
            return $orderNo;
        }
    }


    /**
     * 取消订单
     * @return int
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function cancelOrder(): int
    {
        $time = time() - 600;

        $where = [
            ['create_time', '<', $time],
            ['status', '=', 0]
        ];
        $ids = self::where($where)->select(['id'])->get()->toArray();
        logger('Crontab','crontab')->info('订单过期',[$ids]);
        return self::where($where)->update(['status' => 3]);
    }


    /**
     * 完成订阅订单
     * @param $orderNo
     * @param $payId
     * @return bool
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function completeOrder($orderNo, $payId)
    {
        $orderInfo = self::where(['order_no' => $orderNo, 'status' => 0])->first();
        if (is_null($orderInfo)) {

            return false;
        }
        $subInfo = SubOption::where(['code' => $orderInfo['code']])->first();

        if (is_null($subInfo)) {
            logger()->info('订单信息错误，已经支付成功，但是订阅选项信息没找到', [$orderInfo, $subInfo]);
            return false;
        }


        $renew = SubOption::countRenewDay($subInfo['unit'], $subInfo['quantity']);

        if (!$renew) {
            logger()->info('订单信息错误，已经支付成功，但是订阅选项信息设置出问题', [$orderInfo, $subInfo]);
            return false;
        }


        $updateData = [
            'status' => 1,
            'update_time' => time(),
        ];


        Db::beginTransaction();
        try {

            self::where(['order_no' => $orderNo])->update($updateData);

            $userUpdateData = [
                'role' => 1,
                'update_time' => time(),
                'become_due' =>$orderInfo['expires_date_ms']??strtotime($renew)
            ];

            $rel = User::where(['id'=>$orderInfo['uid']])->update($userUpdateData);
            logger()->info('订阅会员成功',[$updateData,$orderInfo,$subInfo]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollBack();
            recordExceptionLog('订阅订单确定出错',$e->getMessage());
            return false;

        }


    }



}
